<html>
<head>
<title>计算属性和侦听属性的setter</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
</head>
<body>
	<div id="demo">
		<div>{{ fullName }}</div>
		<br/>
		<p>Ask a yes/no question:
			<input v-model="question">
		</p>
		<p>{{answer}}</p>
	</div>
	<script>
	var vm = new Vue({
		el: '#demo',
		data: {
			firstName: 'Foo',
			lastName: 'Bar',
			question:'',
			answer:'I cannot give you an answer until you ask a question!'
		},
		computed: {
			fullName:{ 
				get:function () {
					return this.firstName + ' ' + this.lastName
				},
				set:function(newname){
					var names=newname.split('')
					this.firstName=names[0]
					this,lastName=names[names.length-1]
				}
			}
		},
		watch:{
			question:function(newQuestion,oldQuestion){
				this.answer='Waiting for you to stop typing...',
				this.debouncedGetAnswer()
			}
		},
		created:function(){
			this.debouncedGetAnswer=_.debounce(this.getAnswer, 500)
		},
		methods:{
			getAnswer: function () {
			  if (this.question.indexOf('?') === -1) {
				this.answer = 'Questions usually contain a question mark. ;-)'
				return
			  }
			  this.answer = 'Thinking...'
			  var vm = this
			  axios.get('https://yesno.wtf/api')
				.then(function (response) {
				  vm.answer = _.capitalize(response.data.answer)
				})
				.catch(function (error) {
				  vm.answer = 'Error! Could not reach the API. ' + error
				})
			}
		}
	})
</script>
</body>
</html>